package com.easy.module.system.config;

import cn.hutool.core.util.CharsetUtil;
import com.easy.framework.common.utils.ConvertUtil;
import com.easy.module.system.service.ISysConfService;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.JavaMailSenderImpl;

import java.util.Properties;

@Configuration
public class MailConfig {

    @Bean
    public JavaMailSender javaMailSender(ISysConfService sysConfService) {
        JavaMailSenderImpl mailSender = new JavaMailSenderImpl();

        // QQ邮箱SMTP服务器配置
        mailSender.setHost(sysConfService.getValue("sys.mail.host"));
        mailSender.setPort(ConvertUtil.toInt(sysConfService.getValue("sys.mail.port"), 587));
        mailSender.setUsername(sysConfService.getValue("sys.mail.email"));
        mailSender.setPassword(sysConfService.getValue("sys.mail.code"));
        mailSender.setDefaultEncoding(CharsetUtil.UTF_8);
        mailSender.setProtocol(sysConfService.getValue("sys.mail.protocol"));
        // JavaMail属性配置
        Properties props = mailSender.getJavaMailProperties();
        props.put("mail.transport.protocol", "smtp");
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.starttls.enable", "true");
        props.put("mail.smtp.starttls.required", "true");
        props.put("mail.debug", "true"); // 调试模式
        props.put("mail.smtp.connectiontimeout", 5000);
        props.put("mail.smtp.timeout", 5000);
        props.put("mail.smtp.writetimeout", 5000);

        return mailSender;
    }
}
